package com.wx.util;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 序列化与反序列化工具
 */
public class SerializationUtil {
    private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap();

    private static Objenesis objenesis = new ObjenesisStd();

    private SerializationUtil() {

    }
    //对于消息进行序列化
    public static <T> byte[]  serialzationObj(T t){
        Class<?> aClass = t.getClass();
        Schema<T> schema =(Schema<T>) getSchema(aClass);
        LinkedBuffer allocate = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        byte[] bytes = ProtobufIOUtil.toByteArray(t,schema , allocate);
        return bytes;
    }
    //反序列化
    public static<T> T unSerialzationObj(byte[] data,Class<T> tClass){
        //获得解码的schema
        Schema<T> schema = getSchema(tClass);
        //使用objenesis对对象进行实例化
        T t = objenesis.newInstance(tClass);
        ProtobufIOUtil.mergeFrom(data,t,schema);
        return t;
    }

    private static <T> Schema<T> getSchema(Class<T> tClass){
        Schema<T> tSchema = (Schema<T>) cachedSchema.get(tClass);
        if(tSchema==null){
            Schema<T> schema = RuntimeSchema.getSchema(tClass);
            cachedSchema.put(tClass,schema);
            return schema;
        }
        return tSchema;
    }

}
